const express = require('express')
const app=express()
app.use(require('cors')()) //允许跨域
app.use(express.json()) //识别客户端传递过来的json
const {UserList} = require("./models/db.js")
//增 user
app.put('/api/user', async (req, res) => {
  const userlength = await UserList.countDocuments()
  let length = JSON.stringify(userlength)
  //const userList = await UserList.find().lean()//.length
  const user = await UserList.create({
    id: Number(length)+1,
    username:req.body.username,
    tel:req.body.tel
  })
  res.send(user)
})
//删 user
app.delete('/api/user/:id', async (req, res) => {
  //console.log(req.params.id, req.body);
  const user = await UserList.findByIdAndDelete(req.params.id)
  res.send(user)
})
//改 user
app.put('/api/user/:id', async (req, res) => {
  const user = await UserList.findByIdAndUpdate(req.params.id, req.body)
  res.send(user)
})
//查 user
//获取所有list
app.get('/api/user',async(req,res)=>{
  const list = await UserList.find()
  //res.send('hello')
  res.send(list)
})
//分页查询
app.get('/api/userPage', async(req, res) => {
  const {pageIndex,pageSize} = req.query//.pageSize
  //console.log(pageIndex, pageSize);
  const list = await UserList.find().
  skip((pageIndex-1)*pageSize).
  limit(Number(pageSize))
  //console.log(list);
  res.send(list)
})
//获取list长度
app.get('/api/userLength',async(req,res)=>{
  const length=await UserList.countDocuments()//find().length()//JSON.parse(UserList.find()).length
  //res.sendStatus(length)
  res.send(JSON.stringify(length))
})
//创建list
let id=2
app.post('/api/userlist',async(req,res)=>{
  //let id = Number(UserList.find().pop().id)+1
  /* const list = UserList.find(),
        last=JSON.parse(list).pop(),
        id=last.id+1 */
  id++
  const userlist = await UserList.create({
    id,//:req.body.id,
    username:req.body.username,
    tel:req.body.tel
  })
  res.send(userlist)
})
app.listen(3000,()=>{
  console.log('http://localhost:3000');
})